package com.raos.example.springboot.controller;

import com.raos.example.springboot.MybatisPlusConfig;
import com.raos.example.springboot.dal.model.UserInfo;
import com.raos.example.springboot.service.IUserInfoService;
import com.raos.example.springboot.utils.ConsistentHashing;
import com.raos.example.springboot.utils.SnowFlakeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * 分库分表实战之 用户操作前端控制器
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/8/21 21:05
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class UserInfoController {

    @Autowired
    private IUserInfoService userInfoService;

    private SnowFlakeGenerator snowFlakeGenerator = new SnowFlakeGenerator(1, 1, 1);

    @PostMapping("/batch")
    public void user(@RequestBody List<UserInfo> userInfos) {
        log.info("begin UserInfoController.user");
        Long bizId = null;
        for (UserInfo userInfo : userInfos) {
            bizId = snowFlakeGenerator.nextId();
            userInfo.setBizId(bizId);
        }
        String table = ConsistentHashing.getServer(bizId.toString());
        log.info("批量插入统一入库:{}", table);
        MybatisPlusConfig.TABLE_NAME.set(table);
        userInfoService.saveBatch(userInfos);
    }

    @PostMapping
    public void signal(@RequestBody UserInfo userInfo) {
        Long bizId = snowFlakeGenerator.nextId();
        userInfo.setBizId(bizId);
        //一致性hash算法得到目标表
        String table = ConsistentHashing.getServer(bizId.toString());
        log.info("UserInfoController.signal:{}", table);
        MybatisPlusConfig.TABLE_NAME.set(table);
        userInfoService.save(userInfo);
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString());
        //SnowFlake
        //
    }
}
